package cn.wolfcode.crm.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.wolfcode.crm.domain.Member;
import cn.wolfcode.crm.mapper.MemberMapper;
import cn.wolfcode.crm.query.MemberQueryObject;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMemberService;
import cn.wolfcode.crm.util.MemberAnalysisInfoJson;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PageUtils;

@Service
public class MemberServiceImpl implements IMemberService{
    @Autowired
    private MemberMapper mapper;
    
    public void save(Member entity) {
        //初始化开卡时间
        entity.setStartdate(new Date());
        //初始化状态
        entity.setState(Member.STATUS_NORMAL);

        mapper.insert(entity);
    }

    public void update(Member entity) {

        mapper.updateByPrimaryKey(entity);       

    }

    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);

    }

    public List<Member> list() {
        return mapper.selectAll();
    }

    public Member get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public PageResult query(QueryObject qo) {
       return PageUtils.query(qo,mapper);
    }


    public void changeState(Long id) {
        mapper.changeState(id);
    }

    public void changePassword(Long id, String newpassword) {
        mapper.changePassword(id,newpassword);
    }


    public Member queryByCardno(Long cardno) {
        return mapper.queryByCardno(cardno);
    }


    public MemberAnalysisInfoJson analysisInfo() {
        MemberAnalysisInfoJson info = new MemberAnalysisInfoJson();
        info.setTodayBirthNumber(mapper.queryTodayBirthNumber());
        info.setOtherBirthNumber(mapper.queryOtherBirthNumber());
        info.setTotalMemberNumber(mapper.queryForCount(new MemberQueryObject()));
        info.setTotalBalance(mapper.queryTotalBalance());
        info.setTotalSpend(mapper.queryTotalSpend());
        info.setTop3Member(mapper.queryTop3Member());

        return info;
    }

    public void changeCardno(Long id, Long cardno) {
        mapper.changeCardno(id,cardno);
        //然后查看状态,已挂失就更换为正常
        Member member = mapper.selectByPrimaryKey(id);
        if(member.getState() == 0){
            mapper.changeState(id);
        }
    }
}
